package top.wuyang.springboot3.schoolTimetable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.wuyang.springboot3.base.PageBean;
import top.wuyang.springboot3.base.R;
import top.wuyang.springboot3.schoolTimetable.dao.TbSubjectMapper;
import top.wuyang.springboot3.schoolTimetable.entity.TbSubject;
import top.wuyang.springboot3.schoolTimetable.service.TbSubjectService;
import top.wuyang.springboot3.vo.PageVO;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbSubjectServiceImpl implements TbSubjectService {
    private final TbSubjectMapper tbSubjectMapper;

    private TbSubject queryByName(String sname){
        QueryWrapper<TbSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("sname", sname);
        TbSubject tbSubject = tbSubjectMapper.selectOne(wrapper);
        return tbSubject;
    }

    @Override
    public R<PageVO<TbSubject>> query(PageBean pageBean, TbSubject tbSubject){
        // 分页查询的参数
        IPage<TbSubject> page = new Page<>(pageBean.getPageNumber(),pageBean.getPageSize());
        // 动态sql
        QueryWrapper<TbSubject> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(tbSubject.getSname()), "sname", tbSubject.getSname());
        page = tbSubjectMapper.selectPage(page, wrapper);
        return R.ok(page);
    }

    @Override
    public R<TbSubject> queryById(Integer id){
        TbSubject tbSubject = tbSubjectMapper.selectById(id);
        return tbSubject == null ? R.fail("学科不存在", null) : R.ok("",tbSubject);
    }

    @Override
    public R<String> insert(TbSubject tbSubject){
        // 校验
        TbSubject check = queryByName(tbSubject.getSname());
        if (check != null){
            return R.fail("科目已经存在", null);
        }
        int i = tbSubjectMapper.insert(tbSubject);
        return i == 1 ? R.ok("新增成功", null) : R.fail("新增失败", null);
    }

    @Override
    public R<String> update(TbSubject tbSubject){
        // 校验
        TbSubject check = queryByName(tbSubject.getSname());
        if (check != null && !check.getId().equals(tbSubject.getId())){
            return R.fail("科目已经存在", null);
        }
        int i = tbSubjectMapper.updateById(tbSubject);
        return i == 1 ? R.ok("修改成功", null) : R.fail("修改失败", null);
    }

    @Override
    public R<String> delete(Integer id){
        int i = tbSubjectMapper.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("删除失败", null);
    }


}
